<?php
/**
 * Description of UserMapper
 *
 /*
 * @author     Thibaut Cromphaut and Dimitry Dierickx
 * @copyright  Copyright (c) 2011 Safti-Kado
 */
class Application_Model_KeywordMapper extends Ahs_Model_Mapper
{

    public function __construct(array $options = null)
    {
        parent::__construct($options);
        $this->DbTableName = 'Application_Model_DbTable_Keywords';
    }

    /**
     * @param integer $id
     * @return Application_Model_Keyword
     */
    public function fetchById($id)
    {
        $row = $this->getDbTable()->fetchRow(array('keyword_id = ?' => $id));

        //return $this->_toKeyword($row);
        return $row;
    }
    
    /**
     * @param integer $id
     * @return Application_Model_Keyword
     */
    public function fetchAllKeywordsByShelfId($id)
    {
        $rows = $this->getDbTable()->fetchAll(array('keyword_shelf_id = ?' => $id));
        return $this->_toKeywords($rows);
    }

    /**
     * @return array
     */
    public function fetchAll()
    {        
        $rows = $this->getDbTable()->fetchAll();
        
        return $this->_toKeywords($rows);
    }

    /**
     * @param Application_Model_Keyword $keyword
     */
    public function save(Application_Model_Keyword $keyword)
    {
        $data = array(
            'keyword_label'       => $keyword->Label,
            'keyword_alternatives'=> $keyword->Alternatives,
            'keyword_shelf_id'    => $keyword->ShelfId,
        );

        if (null == $keyword->Id) {
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('keyword_id = ?' => $keyword->Id));
        }
    }
    
    /**
     * @param Zend_Db_Table_Row_Abstract $row
     * @return Application_Model_Keyword 
     */
    private function _toKeyword(Zend_Db_Table_Row_Abstract $row = null)
    {
        $keyword = new Application_Model_Keyword();
        
        if ($row) {
            $keyword->Id           = $row['keyword_id'];
            $keyword->Label        = $row['keyword_label'];
            $keyword->Alternatives = $row['keyword_alternatives'];
            $keyword->ParentId     = $row['keyword_parent_id'];
            $keyword->ShelfId      = $row['keyword_shelf_id'];
        }
        
        return $keyword;
    }

    /**
     * @param Zend_Db_Table_Rowset_Abstract $rows
     * @return array
     */
    private function _toKeywords(Zend_Db_Table_Rowset_Abstract $rows = null)
    {
        $keywords = array();

        if ($rows) {
            foreach ($rows as $row) {
                $keywords[] = $this->_toKeyword($row);
            }
        }
        
        return $keywords;
    }

}